<template>
    <div class="library-location-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入馆藏地名称或地址查询" clearable @clear="handleClearSearch"
                class="search-input" />
            <el-button type="primary" @click="openDialog">新增馆藏地</el-button>
        </div>

        <el-table :data="libraryLocations" stripe border>
            <el-table-column prop="location_name" label="馆藏地名称" />
            <el-table-column prop="address" label="馆藏地地址" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="created_at" label="创建时间" />
            <el-table-column prop="updated_at" label="更新时间" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" @click="openDialog(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />

        <el-dialog v-model="dialogVisible" width="30%" title="编辑馆藏地">
            <el-form :model="currentLibraryLocation" ref="form" label-width="100px">
                <el-form-item label="馆藏地名称" :rules="[{ required: true, message: '请输入馆藏地名称', trigger: 'blur' }]">
                    <el-input v-model="currentLibraryLocation.location_name" placeholder="请输入馆藏地名称" />
                </el-form-item>
                <el-form-item label="馆藏地地址" :rules="[{ required: true, message: '请输入馆藏地地址', trigger: 'blur' }]">
                    <el-input v-model="currentLibraryLocation.address" placeholder="请输入馆藏地地址" />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input type="textarea" v-model="currentLibraryLocation.description" placeholder="请输入描述" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSave">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { libraryLocationApi } from '@/request/apiService';
import { ElMessageBox } from 'element-plus';

const libraryLocations = ref([]);
const currentLibraryLocation = ref({ location_name: '', address: '', description: '' });
const dialogVisible = ref(false);
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取馆藏地列表
const fetchLibraryLocations = async () => {
    try {
        const { data, total: totalCount } = await libraryLocationApi.getLibraryLocationList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
        });
        libraryLocations.value = data;
        total.value = totalCount;
    } catch (error) {
        console.error('获取馆藏地列表失败', error);
    }
};

// 新增或编辑馆藏地
const openDialog = (location = { location_name: '', address: '', description: '' }) => {
    currentLibraryLocation.value = { ...location };
    dialogVisible.value = true;
};

// 保存馆藏地（新增或更新）
const handleSave = async () => {
    const { location_name, address, description } = currentLibraryLocation.value;
    if (!location_name || !address) return;

    try {
        if (currentLibraryLocation.value.location_id) {
            await libraryLocationApi.updateLibraryLocation(currentLibraryLocation.value);
        } else {
            await libraryLocationApi.addLibraryLocation({ location_name, address, description });
        }
        await fetchLibraryLocations();
        dialogVisible.value = false;
    } catch (error) {
        console.error('保存馆藏地失败', error);
    }
};

// 删除馆藏地
const handleDelete = (location) => {
    ElMessageBox.confirm('此操作将永久删除该馆藏地, 是否继续?', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await libraryLocationApi.deleteLibraryLocation({ location_id: location.location_id });
                await fetchLibraryLocations();
            } catch (error) {
                console.error('删除馆藏地失败', error);
            }
        })
        .catch(() => console.log('删除操作已取消'));
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchLibraryLocations();
};

// 分页改变时触发
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchLibraryLocations();
};

// 页面加载时，获取馆藏地数据
onMounted(fetchLibraryLocations);

// 监听搜索变化自动获取数据
watch(search, fetchLibraryLocations);
</script>

<style scoped>
.library-location-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>
